import 'package:center_beijing/config/global_config.dart';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'logutil.dart';
import 'notification.dart';


class HttpUtil {
  static HttpUtil _instance;

  static Dio _dio;
  BaseOptions _baseOptions;
  String session = '';
  static HttpUtil getInstance() {
    if (_instance == null) {
      _instance = new HttpUtil();
    }
    return _instance;
  }

  HttpUtil() {
    _baseOptions = new BaseOptions(
        baseUrl: GlobalConfig.baseUrl,
        connectTimeout: GlobalConfig.connectTimeout,
        receiveTimeout: GlobalConfig.receiveTimeout
        );
    _dio = new Dio(_baseOptions);

    _dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options,handler) async {
      // 在请求被发送之前做一些事情
      Map<String, String> map = new Map();
      if(options.path.indexOf('rheaservice')!=-1){
        map['Content-Type'] = 'application/json; charset=UTF-8';
      }else{
        map['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
      }
      map["user-agent-tag"] = 'app';
      map["ZJQFSESSION"] = GlobalConfig.session;
      map["Cookie"] = 'SESSION='+GlobalConfig.session;
      map["Authorization"] =GlobalConfig.token;
      options.headers.addAll(map);
      return handler.next(options); //continue
      // 如果你想完成请求并返回一些自定义数据，可以返回一个`Response`对象或返回`dio.resolve(data)`。
      // 这样请求将会被终止，上层then会被调用，then中返回的数据将是你的自定义数据data.
      //
      // 如果你想终止请求并触发一个错误,你可以返回一个`DioError`对象，或返回`dio.reject(errMsg)`，
      // 这样请求将被中止并触发异常，上层catchError会被调用。
    }, onResponse: (Response response,handler) async {
      // 在返回响应数据之前做一些预处理
      // GlobalConfig.token = response.headers["authorization"][0];
      if(response.headers['set-cookie']!=null){
        var cookie = response.headers['set-cookie'][0].toString().split(";")[0];
        var cookieIndex = cookie.indexOf('SESSION');
        session = cookie.substring(cookieIndex+8);
        GlobalConfig.session = session;
      }
      if(response.headers['authorization']!=null){
        GlobalConfig.token = response.headers['authorization'][0].toString();
      }
      return handler.next(response); // continue
    }, onError: (DioError e,handler) async {
      // 当请求失败时做一些预处理
      if(!(e.error is String)&&e.error.osError.errorCode==51){
        Fluttertoast.showToast(msg: '网络连接失败,请检查网络!');
      }else if(e.response!=null&&e.response.statusCode==401){
        Fluttertoast.showToast(msg: '登录超时，请重新登录');
      }else if(e.response!=null&&e.response.statusCode==500){
        Fluttertoast.showToast(msg: '系统错误,请联系管理员');
      }else if(e.response!=null&&e.response.statusCode==412){
        Fluttertoast.showToast(msg: e.response.data);
      }else if(e.response!=null&&e.response.statusCode==404){
        Fluttertoast.showToast(msg: '404错误');
      }else if(e.error.osError!=null&&e.error.osError.errorCode==8){
        Fluttertoast.showToast(msg: '网络链接失败');
      }else{
        if(e.type == DioErrorType.other){
          Fluttertoast.showToast(msg: '网络连接失败,请检查网络!');
        }else{
          Fluttertoast.showToast(msg: '返回数据错误');
        }

      }
      return handler.next(e); //continue
    }));
  }

  get(String url, {params}) async {
    var result;
    try {
      Response response = await _dio.get(url, queryParameters: params);
      result=response.data;
      LogUtil.d(result);
    } catch (e) {
      print('get请求发送错误$e');

    }
    return result;
  }

  post(String url, data,{onSendProgress}) async {
    var result;
    try {
      Response response = await _dio.post(url, data: data,onSendProgress: onSendProgress);
      result=response.data;
    } on DioError catch (e) {
      print('post请求发送错误$e');
    }
    return result;
  }
  post2(String url, data,{onSendProgress}) async {
    var result;
    try {
      int i = 0;
      data.forEach((key, value) {
        if(i == 0){
          url = "${url}?${key}=${value}";
        }else{
          url = "${url}&${key}=${value}";
        }
        i++;
      });
      Response response = await _dio.post(url, queryParameters: data,onSendProgress: onSendProgress);
      result=response.data;
    } on DioError catch (e) {
      print('post请求发送错误$e');
    }
    return result;
  }

  put(String url, data,{onSendProgress}) async {
    var result;
    try {
      Response response = await _dio.put(url, data: data,onSendProgress: onSendProgress);
      result=response.data;
    } on DioError catch (e) {
      print('put请求发送错误$e');
    }
    return result;
  }
  put2(String url, data,{onSendProgress}) async {
    var result;
    try {
      Response response = await _dio.put(url, queryParameters: data,onSendProgress: onSendProgress);
      result=response.data;
    } on DioError catch (e) {
      print('put请求发送错误$e');
    }
    return result;
  }
  delete(String url,{data,onSendProgress}) async {
    var result;
    try {
      Response response = await _dio.delete(url, data: data);
      result=response.data;
    } on DioError catch (e) {
      print('put请求发送错误$e');
    }
    return result;
  }

}
